package spirit.io.nio.ifeve.channel;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author eric - 好好学习，天天向上！
 * @date 2021/12/28
 * @description file channel
 */
public class FileChannelDemo {
    public static void main(String[] args) {
        RandomAccessFile accessFile;
        try {
            accessFile = new RandomAccessFile("data/nio-data.txt", "rw");
            FileChannel fileChannel = accessFile.getChannel();

            ByteBuffer byteBuffer = ByteBuffer.allocate(48);
            // 将数据读到buffer中
            int byteRead = fileChannel.read(byteBuffer);
            while (byteRead != -1) {
                System.out.println("Read" + byteRead);
                byteBuffer.flip();
                while (byteBuffer.hasRemaining()) {
                    System.out.print((char) byteBuffer.get());
                }
                byteBuffer.clear();
                byteRead = fileChannel.read(byteBuffer);
            }
            accessFile.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
